package com.example.chuntiao.cophook.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.signature.ObjectKey;
import com.example.chuntiao.cophook.R;
import com.example.chuntiao.cophook.exception.LogInException;
import com.example.chuntiao.cophook.mytools.HttpTool;
import com.example.chuntiao.cophook.mytools.MyApp;

import java.io.IOException;
import java.net.ConnectException;

public class PhotoActivity extends AppCompatActivity {

    final static int REQ_FOR_CHOOSE_ACTI = 0;
    final static int REQ_FRO_crop = 1;
    TextView txtToChangePhoto;
    ImageView photo;
    MyApp mApp;

    private static final String TAG = "PhotoActivity";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQ_FOR_CHOOSE_ACTI:
                if (resultCode == RESULT_OK) {
                    Uri uri = null;
                    if (data != null) {
                        uri = data.getData();
                        cropPhoto(uri);
                    }
                }
                break;
            case REQ_FRO_crop:
                if (resultCode == RESULT_OK) {

                    Bundle bundle = data.getExtras();
                    Bitmap bitmap = bundle.getParcelable("data");
                    photo.setImageBitmap(bitmap);


                    new AsyncTask<Bitmap, Void, Integer>() {
                        ProgressDialog progressDialog;
                        AlertDialog dialog;

                        @Override
                        protected void onPreExecute() {
                            super.onPreExecute();
                            progressDialog = ProgressDialog.show(PhotoActivity.this, "稍等", "头像上传中");
                            dialog = new AlertDialog.Builder(PhotoActivity.this)
                                    .setPositiveButton(R.string.yse, null)
                                    .setMessage("未知错误")
                                    .create();
                        }

                        @Override
                        protected Integer doInBackground(Bitmap... params) {
                            try {
                                return HttpTool.sendOkHttpUpload(PhotoActivity.this, params[0], HttpTool.UPLOAD_PEOPLE_IMG, null);
                            } catch (LogInException e) {
                                dialog.setMessage("自动登录失败，请手动登录");
                            } catch (ConnectException e) {
                                dialog.setMessage("联网失败，请检查网络");
                            } catch (java.net.SocketTimeoutException e) {
                                e.printStackTrace();
                                dialog.setMessage("连接超时");
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Integer result) {
                            progressDialog.dismiss();
                            progressDialog = null;
                            if (result != null) {

                                dialog = null;
                                Intent intent = new Intent();
                                intent.putExtra("img_ver", result.intValue());
                                setResult(RESULT_OK, intent);
                                finish();
                            } else
                                dialog.show();
                        }
                    }.execute(new Bitmap[]{bitmap});

                }
                break;

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_poto);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mApp = (MyApp) getApplication();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        txtToChangePhoto = (TextView) findViewById(R.id.txt_change_photo);
        photo = (ImageView) findViewById(R.id.img_the_photo);
        txtToChangePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent=new Intent(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT
//                intent.setType("image/*");
                Intent intent = new Intent(
                        Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                startActivityForResult(intent, REQ_FOR_CHOOSE_ACTI);

            }
        });
        if (mApp.getImgVer() != -1)
            Glide.with(PhotoActivity.this).load(MyApp.HOST_URL + "image/" + "u_" + mApp.getUid())
                    .apply(RequestOptions.signatureOf(new ObjectKey(mApp.getImgVer()))).into(photo);
    }

    private void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQ_FRO_crop);
    }
}
